package utils

import com.google.gson.Gson
import com.intellij.jarRepository.services.artifactory.Endpoint
import kotlinx.coroutines.*
import org.jetbrains.uast.withMargin
import java.util.*

import javax.swing.*
import kotlin.collections.HashMap
import kotlin.math.abs
import kotlin.math.roundToInt

class Ti_FHandler(table: JTable) : FRefreshHandler(table) {
    private val codes = ArrayList<String>()
    private val calendar = Calendar.getInstance()
    private val job = SupervisorJob()
    private val codeMap = HashMap<String, String>()


    private fun getDay() = calendar.get(Calendar.DAY_OF_WEEK)

    private fun getHour() = calendar.get(Calendar.HOUR_OF_DAY)

    private fun isNotWeekend() = getDay() != Calendar.SUNDAY && getDay() != Calendar.SATURDAY

    private fun getMinute() = calendar.get(Calendar.MINUTE)

    private fun updateTime() {
        calendar.timeInMillis = System.currentTimeMillis()
    }

    override fun handle(code: List<String>) {
        if (code.isEmpty()) {
            return
        }
        LogUtil.info("Leeks Update ...")
        clear()
        codes.clear()
        codes.addAll(code)
        getFundName(code)
        //排序，按加入顺序
        for (s in codes) {
            updateData(FBean(s))
        }
        CoroutineScope(job).launch {
            while (true) {
                updateTime()
                val hour = getHour()
                val minute = getMinute()
                if (hour >= 15 && minute > 4) {//大于3点
                    stepAction()
                    return@launch
                } else if (hour == 11 && minute > 34) {//大于11.30
                    delay(600 * 1000)//10分钟
                } else if (hour == 12 && minute < 59) {//等于12点
                    if (minute >= 50) delay(((60 - minute) * 60 * 1000).toLong())
                    else delay(600 * 1000)//10分钟
                } else {
                    stepAction()
                    delay(60 * 1000)//1分钟
                }
                if (!isNotWeekend()) return@launch
            }
        }
    }

    private fun getFundName(code: List<String>) {
        codeMap.clear()
        for (s in code) {
            try {
                val requestUrl = "https://fundsuggest.eastmoney.com/FundSearch/api/FundSearchAPI.ashx?m=1&key=$s"
                val iBean = requestUrl.getIBean()
                if (iBean.datas.size >= 1)
                    codeMap[s] = iBean.datas[0].jp.toLowerCase()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun String.getIBean(): InfoBean = with(HttpClientPool.getHttpClient().get(this)) {
        gson.fromJson(this, InfoBean::class.java)
    }

    private fun String.getFBean(): FBean = with(HttpClientPool.getHttpClient().get(this)) {
        gson.fromJson(substring(8, length - 2), FBean::class.java)
    }

    private fun stepAction() {
        updateTime()
        //        LogUtil.info("Leeks 刷新基金数据.");
        //CoroutineScope(job).launch {
        val sb = StringBuffer("Update In ");
        sb.append(getHour()).append(":").append(getMinute()).append(" ")
        var fundTrend = ""
        for (s in codes) {
            try {
                val bean = "http://fundgz.1234567.com.cn/js/$s.js?rt=${System.currentTimeMillis()}".getFBean()
                val gszzlStr = if (bean.gszzl.startsWith("-")) bean.gszzl else bean.gszzl

                val value = (abs(gszzlStr.toDouble()) * 10).toInt()
                val finVal = when (value % 10) {
                    in 0..3 -> value / 10
                    in 4..7 -> value
                    in 8..9 -> (value + 10) / 10
                    else -> 0
                }

                if (gszzlStr.toDouble() < 0) sb.append("\'")
                val fixFundName = codeMap[s]!![0] + dealName(codeMap[s]!!)
                sb.append(fixFundName.toUpperCase()).append(finVal)
                updateData(bean)
                updateUI()
            } catch (e: Exception) {
                LogUtil.info(Arrays.toString(e.stackTrace))
            }
        }
        LogUtil.info(sb.toString())
        //}
//        for (s in codes) {
//            Thread {
//                try {
//                    val result = HttpClientPool.getHttpClient().get("http://fundgz.1234567.com.cn/js/" + s + ".js?rt=" + System.currentTimeMill())
//                    val json = result.substring(8, result.length - 2)
//                    val bean = gson.fromJson(json, FBean::class.java)
//                    updateData(bean)
//                    updateUI()
//                } catch (e: Exception) {
//                    e.printStackTrace()
//                }
//            }.start()
//        }
    }

    private fun dealName(s: String) = when {
        s.contains("5g") -> "5"
        s.contains("yy") -> "y"
        s.contains("xny") -> "n"
        s.contains("cz") -> "c"
        s.contains("hlw") -> "h"
        s.contains("xxcx") -> "x"
        else -> ""
    }


    companion object {
        private val gson = Gson()
    }
}
